package com.mitac.mcd.cs.mobiletracking.socketserver.util;


import java.io.IOException;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;

import com.mitac.mcd.cs.mobiletracking.socketserver.MobileServer;

public class MemcacheUtil
{
	//创建一个 memcached 客户端对象
    //public static MemCachedClient memCachedClient = new MemCachedClient();
    private static MemcachedClient memCachedClient = null;
	
    public static void init(){
    	String server = MobileServer.ConfigProperties.get("MEMCACHED_SERVER").toString();
    	MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses(server));
    	builder.setConnectionPoolSize(30);
    	try {
			memCachedClient = builder.build();
		} catch (IOException e) {
			BusinessUtil.aLogger.error("MemcacheUtil Error:"+e);
			BusinessUtil.logException(null, -1, -1, MobileServer.IP, "E011", ""+e);
		}
    }
    
    public static MemcachedClient getMemCachedClient() {
    	if(memCachedClient==null) init();
		return memCachedClient;
	}



	// 创建  memcached连接池
    static{
    	/*// 指定memcached服务地址 
    	String[] servers = null;
    	if (server.indexOf(",")>=0){
    		servers = server.split(",");
    	}else{
    		servers = new String[]{server};
    	}
    	//从连接池获取一个连接实例
    	SockIOPool pool = SockIOPool.getInstance();
    	// 设置服务器和服务器负载量
    	pool.setServers(servers);
    	// 设置一些基本的参数
    	//设置初始连接数5   最小连接数 5   最大连接数 250
    	//设置一个连接最大空闲时间6小时
    	pool.setInitConn(5);
    	pool.setMinConn(5);
    	pool.setMaxConn(200);
    	pool.setMaxIdle(1000*60*60*1);
    	// 设置主线程睡眠时间
    	// 每隔30秒醒来  然后
    	// 开始维护 连接数大小
    	pool.setMaintSleep(30);
    	// 设置tcp 相关的树形
    	// 关闭nagle算法
    	// 设置 读取 超时3秒钟  set the read timeout to 3 secs
    	// 不设置连接超时
	    pool.setNagle( false );
	    pool.setSocketTO(3*1000);
	    pool.setSocketConnectTO(0);
	    // 开始初始化 连接池
	    pool.initialize();*/
    }
    
    public static void main(String args[]) throws InterruptedException, TimeoutException, MemcachedException, IOException{
    	MemcachedClientBuilder builder = new XMemcachedClientBuilder(AddrUtil.getAddresses("127.0.0.1:11211"));
    	builder.setConnectionPoolSize(50);
    	MemcachedClient mc = builder.build();
    	mc.flushAll();
    	BusinessUtil.aLogger.info(mc.get("U38e7d822ced5"));
    	
    }
    
}
